package main

import (
	"flag"
	"fmt"
	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/logx"
	"go-zero-project/common/global"
	"go-zero-project/services/project/rpc/internal/config"
	"go-zero-project/services/project/rpc/internal/initialize/nacos"
	"go-zero-project/services/project/rpc/internal/svc"
	"os"

	"go-zero-project/services/project/rpc/internal/server"
	"go-zero-project/services/project/rpc/pb"

	"github.com/zeromicro/go-zero/core/service"
	"github.com/zeromicro/go-zero/zrpc"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
)

func main() {
	flag.Parse()
	// 1.根据环境变量读取不同配置文件
	configPath := "services/project/rpc/etc/project-rpc-%s.yaml"
	configEnv := os.Getenv(global.GoENV)
	if len(configEnv) < 1 {
		configEnv = global.DefaultEnv
	}
	configPath = fmt.Sprintf(configPath, configEnv)
	configFile := flag.String("f", configPath, "the config file")
	logx.Infof(" read %s file profile:%s ...", configPath, configEnv)
	// 2.绑定配置
	var c config.Config
	conf.MustLoad(*configFile, &c)
	ctx := svc.NewServiceContext(c)
	s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
		// 注册rpc
		pb.RegisterProjectRpcServer(grpcServer, server.NewProjectRpcServer(ctx))
		if c.Mode == service.DevMode || c.Mode == service.TestMode {
			reflection.Register(grpcServer)
		}
	})
	defer s.Stop()
	// 3.服务注册
	nacos.RegisterNacos(c)
	logx.Infof("Starting rpc server %s at %s...", c.Name, c.ListenOn)
	s.Start()
}
